
package com.jf.cloud.search.listener;

import cn.hutool.core.collection.CollUtil;
import cn.throwx.canal.gule.model.CanalBinLogResult;
import com.jf.cloud.api.product.constant.CategoryLevel;
import com.jf.cloud.api.product.feign.CategoryFeignClient;
import com.jf.cloud.api.product.feign.ProductFeignClient;
import com.jf.cloud.common.constant.Constant;
import com.jf.cloud.common.i18n.LanguageEnum;
import com.jf.cloud.common.product.bo.EsCategoryBO;
import com.jf.cloud.common.product.bo.EsProductBO;
import com.jf.cloud.common.product.vo.CategoryLangVO;
import com.jf.cloud.common.product.vo.CategoryVO;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.search.bo.CategoryBO;
import com.jf.cloud.search.util.EsSearchUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zz
 * @date 2020/11/13
 */
@Component
public class CategoryCanalListener extends BaseCanalBinlogEventThrowExceptionProcessor<CategoryBO> {

    private static final Logger log = LoggerFactory.getLogger(CategoryCanalListener.class);

    @Autowired
    private CategoryFeignClient categoryFeignClient;
    @Autowired
    private ProductFeignClient productFeignClient;

    /**
     * 更新分类，删除商品索引，再重新构建一个
     * @param result
     */
    @Override
    protected void processUpdateInternal(CanalBinLogResult<CategoryBO> result) {
        CategoryBO afterData = result.getAfterData();
        boolean updateCategoryName = Objects.equals(Constant.PLATFORM_SHOP_ID, afterData.getShopId()) && afterData.getLevel().equals(CategoryLevel.THIRD.value());
        boolean updateShopCategoryName = !Objects.equals(Constant.PLATFORM_SHOP_ID, afterData.getShopId()) && afterData.getLevel().equals(CategoryLevel.SECOND.value());
        boolean isUpdate = updateCategoryName || updateShopCategoryName;
        // 非平台三级分类或商家二级分类，则不需要更改分类名
        if (!isUpdate) {
            return;
        }

        EsProductBO esProductBO = new EsProductBO();
        ServerResponseEntity<CategoryVO> categoryResponse = categoryFeignClient.getByCategoryId(afterData.getCategoryId());
        if (categoryResponse.isFail()) {
            logger.error("分类id为：{}的分类数据异常", afterData.getCategoryId());
            return;
        }
        CategoryVO categoryVO = categoryResponse.getData();
        if (CollUtil.isEmpty(categoryVO.getCategoryLangList())) {
            logger.error("分类id为：{}的分类国际化数据异常", afterData.getCategoryId());
            return;
        }
        Map<Integer, String> categoryMap = categoryVO.getCategoryLangList().stream().collect(Collectors.toMap(CategoryLangVO::getLang, CategoryLangVO::getName));
        // 平台分类
        if (Objects.equals(Constant.PLATFORM_SHOP_ID, afterData.getShopId()) && afterData.getLevel().equals(CategoryLevel.THIRD.value())) {
            esProductBO.setCategory(new EsCategoryBO());
            esProductBO.getCategory().setCategoryNameZh(categoryMap.get(LanguageEnum.LANGUAGE_ZH_CN.getLang()));
            esProductBO.getCategory().setCategoryNameEn(categoryMap.get(LanguageEnum.LANGUAGE_EN.getLang()));
        }
        // 商家分类
        else if (!Objects.equals(Constant.PLATFORM_SHOP_ID, afterData.getShopId()) && afterData.getLevel().equals(CategoryLevel.SECOND.value())){
            esProductBO.setShopCategory(new EsCategoryBO());
            esProductBO.getShopCategory().setCategoryNameZh(categoryMap.get(LanguageEnum.LANGUAGE_ZH_CN.getLang()));
            esProductBO.getShopCategory().setCategoryNameEn(categoryMap.get(LanguageEnum.LANGUAGE_EN.getLang()));
        }
        List<Long> spuIds = getSpuIdsByCategoryId(afterData);
        EsSearchUtil.esUpdateSpuBySpuIds(spuIds, esProductBO);
    }

    /**
     * 根据分类信息，获取分类下的商品Id列表
     * @param category
     * @return
     */
    private List<Long> getSpuIdsByCategoryId(CategoryBO category) {
        ServerResponseEntity<List<Long>> spuIdResponse = null;
        // 平台分类
        if (Objects.equals(category.getShopId(), Constant.PLATFORM_SHOP_ID)) {
            spuIdResponse = productFeignClient.getSpuIdsByCategoryIds(Collections.singletonList(category.getCategoryId()));
        } else {
            spuIdResponse = productFeignClient.getSpuIdsByShopCategoryIds(Collections.singletonList(category.getCategoryId()));
        }
        return spuIdResponse.getData();
    }
}
